package net.chowda.castcluster.provider;

import net.chowda.castcluster.Video;
import net.chowda.castcluster.VideoSource;
import net.chowda.castcluster.CastVideoItem;
import net.chowda.castcluster.util.CachedGetMethod;
import net.chowda.castcluster.util.RSSFeedAggregator;
import net.chowda.castcluster.util.CorruptFeedException;

import java.util.List;
import java.util.ArrayList;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;

/**
 */
public class RevverProvider extends WebFeedProvider {
    String userRssUrl       = "http://feeds.revver.com/2.0/mrss/flash/user/";
    String userUrl          = "http://one.revver.com/account/show/";
    String fetchUrl         = "http://media.revver.com/qt;download/";
    String thumbUrl         = "http://frame.revver.com/frame/170x128/";
    String videoDetailUrl   = "http://one.revver.com/watch/";

    Pattern descPattern     = Pattern.compile("id=\"video_description\"\\s?.*?>(.*?)</p>",  Pattern.DOTALL | Pattern.MULTILINE);
    Pattern titlePattern    = Pattern.compile("video_title\".*?>(.*?)</h2>",                Pattern.DOTALL | Pattern.MULTILINE);
    Pattern authorPattern   = Pattern.compile("<h3>\\s*<a href=\"/account/show/.*?\">(.*?)</a></h3>",           Pattern.DOTALL | Pattern.MULTILINE);
    Pattern datePattern     = Pattern.compile("</strong> since\\s*<strong>(.*?)</strong>.*?</p>", Pattern.DOTALL | Pattern.MULTILINE);

    public String getProviderFeed(String url) {
        try {
            return RSSFeedAggregator.createPodcastFromVideos("revver", "revver", getProviderVideos(url));
        } catch (CorruptFeedException e) {
            throw new RuntimeException(e);
        }
    }

    public List<Video> getProviderVideos(String url) {
        String itemType = url.split("\\|")[1];
        String itemId = url.split("\\|")[2];

        List<Video> videos = new ArrayList<Video>(1);
        if ("video".equals(itemType)) {
            CastVideoItem item = new CastVideoItem();
            String body = getResponseBodyForVidId(itemId);
            item.setAuthor(firstMatch(body, authorPattern));
            item.setAvailable(true);
            item.setDescription(firstMatch(body, descPattern));
            item.setId(url);
            item.setLengthInSeconds(0);
            item.setThumbnailUrl(thumbUrl + itemId + ".jpg");
            item.setTimeUploaded(null);
            item.setTitle(firstMatch(body, titlePattern));
            item.setUrl(fetchUrl + itemId + ".mov");
            item.setVidSize(0);
            item.setVidType("video/quicktime");

            videos.add(item);
        } else if("user".equals(itemType)) {
            videos = getVideosFromRss(userRssUrl + itemId);
            // change urls from swf to quicktime
            for (Video video : videos) {
                CastVideoItem item = (CastVideoItem) video;
                String swfUrl = item.getUrl();
                Pattern pattern = Pattern.compile("mediaId=(\\d.*)");
                Matcher matcher = pattern.matcher(swfUrl);
                if (matcher.find()) {
                    String vidId = matcher.group(1);
                    item.setUrl("http://media.revver.com/qt;download/" + vidId + ".mov");
                    item.setVidType("video/quicktime");
                }
            }
        }
        return videos;
    }

    private String firstMatch(String body, Pattern pattern) {
        String s = null;
        if (body != null) {
            Matcher matcher = pattern.matcher(body);
            if (matcher.find()) {
                s = matcher.group(1);
            }
        }
        return s;
    }

    public static void main(String[] args) {
        new RevverProvider().getProviderSourceForCCUrl("rv|video|231853");
    }

    public VideoSource getProviderSourceForCCUrl(String url) {
        VideoSource videoSource = new VideoSource();
        if(url.contains("user")) {
            videoSource.setCcUrl(url);
            String userId = url.split("\\|")[2];
            videoSource.setUrl(userUrl + userId);
            videoSource.setProvider(this);
            videoSource.setVideos(getProviderVideos(url));

            videoSource.setName("Revver user - " + userId);
        } else {
            videoSource.setCcUrl(url);
            String vidId = url.split("\\|")[2];
            videoSource.setUrl(videoDetailUrl + vidId);
            videoSource.setProvider(this);
            videoSource.setVideos(getProviderVideos(url));

            String body = getResponseBodyForVidId(vidId);
            videoSource.setName("Revver vid - " + firstMatch(body, titlePattern));
        }

        return videoSource;
    }

    private String getResponseBodyForVidId(String vidId) {
        String body = null;
        HttpClient hc = new HttpClient();
        CachedGetMethod get = new CachedGetMethod(videoDetailUrl + vidId);
        try {
            hc.executeMethod(get);
            body = get.getResponseBodyAsString();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;
    }

    // this isn't used yet.
    public List<VideoSource> getProviderSourcesForWebUrl(String url) {
        return null;
    }
}
